package MemberService

import (
	"context"
	"gdshop-back-end-go/client-api/app/request/MemberReq"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/response"
	"gdshop-back-end-go/common/wxpayHelper"
	"github.com/gogf/gf/frame/g"
)

func WechatBind(ctx context.Context, parames *MemberReq.WechatBind) *response.JsonResponse {
	wxoa := wxpayHelper.GetWxOa()
	token, err := wxoa.Code2AuthToken(ctx, parames.Code)
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	count, err := toolsDb.GetUnSafaTable(ctx, "member_wechat").Where("member_id", parames.MemberId).Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	tmpDb := toolsDb.GetUnSafaTable(ctx, "member_wechat")
	if count > 0 {
		update, err := tmpDb.Where("member_id", parames.MemberId).Update(g.Map{
			"openid": token.OpenID,
		})
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		affected, err := update.RowsAffected()
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		if affected < 1 {
			return response.FailByRequestMessage(nil, "绑定失败")
		}
	} else {
		id, err := tmpDb.InsertAndGetId(g.Map{
			"member_id": parames.MemberId,
			"openid":    token.OpenID,
		})
		if err != nil {
			return response.FailByRequestMessage(nil, err.Error())
		}
		if id < 1 {
			return response.FailByRequestMessage(nil, "绑定失败02")
		}
	}
	return response.SuccessByRequestMessage(nil, "绑定成功")
}
